package com.cisco.nm.pf.dbservice.dbutil;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;

import org.codehaus.jettison.json.JSONObject;

/**
 * Class to perform database operations.
 * @author sivravis
 *
 */

public abstract class DatabaseUtil {

	private static final String DB_PROPS = "resources/dbservice.properties";
	private static final Properties props = new Properties();
	
	/**
	 * Constructor called during class load. reads from the property file
	 * 
	 *  
	 */
	public DatabaseUtil() {
		try {
			props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(DB_PROPS));
		} catch (IOException e) {			
			e.printStackTrace();
		}
	}
	/**
	 * API to get connection.
	 */
	protected Connection getConnection(Map<String,String> usermap){
		Connection con = null;
		System.out.println("trying to get connection ...... ");
		try {
			DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
			con = DriverManager.getConnection(
					"jdbc:oracle:thin:@"+props.getProperty("serverip")+":"+props.getProperty("port")+":" +usermap.get("sid"), 
					usermap.get("username"), 
					usermap.get("password"));
			System.out.println("connection = " +con);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return con;
	}
	public abstract JSONObject executeQuery(Map<String,String> usermap,String query);
	/**
	 * Api to close connection
	 * @return
	 */
	protected void close(Connection con){
		if(con != null){
			try {
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("connection closed...... ");
	}
}
